﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WebDUPlugIn.WebDUReporter
{
    class ExtractedElements
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static Dictionary<string, string> _extarctedDataList = new Dictionary<string, string>();
        private static int _writeCount=0;

        public static void AddDataToDictionary(string url, string text)
        {
            lock (_extarctedDataList)
            {
                _extarctedDataList[url] = text;
            }
        }
        

        public static void DumpDictionarytoFile()
        {
            DateTime currentDay = DateTime.Now;
            string dir = String.Format("C:\\Crawler\\Date_{0}_{1}_{2}", currentDay.Day,currentDay.Month,currentDay.Year);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            string fileName = string.Format("{0}\\Entities{1}.csv",dir,_writeCount);
            StreamWriter fs = null;
            if (!File.Exists(fileName))
            {
                //File.Delete(fileName);
                fs = File.CreateText(fileName);
            }
            else
            {
                fs = File.AppendText(fileName);
            }

            try
            {
                
                //var sw = new StreamWriter(fs);
                lock (_extarctedDataList)
                {
                    foreach (KeyValuePair<string, string> pair in _extarctedDataList)
                    {
                        fs.WriteLine("{0};{1}", pair.Value, pair.Key);
                    }
                    _extarctedDataList.Clear();
                }

                fs.Close();

            }
            catch (IOException e)
            {
                log.FatalFormat(" Exception during report generation.. {0} ", e.ToString());
            }
        }
    }
}
